<!--  -->
<template>
  <el-dialog :title="$t('custom.component.columns.filterSettings')"
             :visible.sync="dialogVisible"
             width="69rem"
             append-to-body
             v-if="dialogVisible"
             class="block-model-dialog"
             :before-close="handleClose">
    <div>
      <TypeFilter :dataForm='dataForm'
                  :scriptItem='scriptItem'
                  :originDataId='gadgetId'
                  :originDataType='`widget`'
                  :isShowCaseSensitiveBase="true"
                  ref="typeFilter"
                  @update='updateData'></TypeFilter>
    </div>
    <span slot="footer"
          class="dialog-footer">
      <el-button size="mini"
                 @click="handleClose">{{$t('cancel ')}}</el-button>
      <el-button size="mini"
                 type="primary"
                 @click="saveFilters">{{$t('ok ')}}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import TypeFilter from '@/components/script-render/components/type-filter'
import { filterJson } from './filter-json'
import { generalConvertJsonToSQL } from '@/utils/common'

export default {
  inject: {isQueryModel:{default:false}},
  components: { TypeFilter },
  props: {
    slicer: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      dialogVisible: false,
      dataForm: null,
      scriptItem: filterJson,
      gadgetId: null,
      gadgetSetting: {}
    }
  },
  methods: {
    getGadgetSetting () {
      if (Object.keys(this.gadgetSetting).length > 0) {
        return false
      }
      let param = {
        pageId: this.$getQuery('pageid'),
        gadgetId: this.gadgetId
      }
      this.$interface.reports.getReportDataInfo(param)
        .then(({ data: res }) => {
          if (res.config) {
            this.gadgetSetting = Object.assign({}, res.config)
          }
        }).catch(() => { })
    },
    queryKeyOptions () {
      this.scriptItem.keyArray = []
      this.scriptItem.IsSlicer = false
      const params = {
        gadgetId: this.gadgetId,
        ...this.slicer
      }
      this.$interface.reports.getFieldsListCacheApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            // return this.$message.error(res.msg)
            return false
          }
          res.data.forEach(item => {
            this.scriptItem.keyArray.push({
              label: item.name,
              value: item.name,
              type: item.type
            })
          })
        }).catch(() => {
          this.scriptItem.keyArray = []
        })
    },
    init (gadgetId) {
      this.gadgetId = gadgetId
      this.openDialog()
    },
    openDialog () {
      this.queryKeyOptions()
      this.queryFilterOptions()
      this.getGadgetSetting()
      this.dialogVisible = true
    },
    handleClose (done) {
      this.dialogVisible = false
      this.isSave = false
    },
    saveFilters () {
      if (this.$refs.typeFilter.checkdataArr()) {
        this.dialogVisible = false
        this.isSave = true
      }
    },
    async updateData (val) {
      if (this.isSave) {
        const filterSql = generalConvertJsonToSQL(val[this.scriptItem.text])
        let otherParam = {
          gadgetId: this.gadgetId,
          filterSql: filterSql,
          filterJson: val[this.scriptItem.text]
        }
        if (this.isQueryModel && this.isQueryModel()) {
          otherParam['type'] = 'widget'
        } else {
          otherParam['type'] = 'gadget'
        }
        if (this.$store.state.isAttendanceSummaryWidget) {
          otherParam['type'] = 'widget'
        } else {
          otherParam['pageId'] = this.$getQuery('pageid')
        }
        if (this.filterIndex !== -1) {
          const params = {
            ...otherParam,
            id: this.filterIndex
          }
          const { data: res } = await this.$interface.reports.putFilterApi(params)
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data) {
            // this.$message.success(res.msg)
          }
        } else {
          const params = {
            ...otherParam
          }
          const { data: res } = await this.$interface.reports.postFilterApi(params)
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data) {
            this.$message.success(res.msg)
          }
        }
        try {
          let removeIndex = -1
          if (!this.gadgetSetting.hasOwnProperty('filters')) {
            this.gadgetSetting['filters'] = []
          }
          for (let index = 0; index < this.gadgetSetting.filters.length; index++) {
            if (this.gadgetSetting.filters[index].gadgetid === this.gadgetId) {
              removeIndex = index
            }
          }
          if (removeIndex !== -1) {
            this.gadgetSetting.filters.splice(removeIndex, 1, {
              gadgetid: this.gadgetId,
              filter: filterSql
            })
          } else {
            this.gadgetSetting.filters.push({
              gadgetid: this.gadgetId,
              filter: filterSql
            })
          }
          this.$emit('updateDataInfo', this.gadgetSetting)
        } catch (error) { }
        this.$emit('updateQuery')
        this.filterIndex = -1
      }
    },
    queryFilterOptions () {
      const _self = this
      this.filterIndex = -1
      this.dataForm = { filters: JSON.parse(JSON.stringify(this.scriptItem.defaultValue)) }
      const params = {
        pageId: _self.$store.state.isAttendanceSummaryWidget ? '' : (this.$getQuery('pageid')),
        gadgetId: _self.gadgetId
      }
      _self.$interface.reports.getFilterDetailApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return _self.$message.error(res.msg)
          }
          if (res.data) {
            _self.filterIndex = res.data.id
            _self.dataForm = { filters: res.data.filterJson }
          }
        })
        .catch(() => { })
    }
  }
}
</script>

<style scoped>
</style>
